package com.star.service;

import com.star.exception.ServiceException;
import com.star.exception.SystemException;
import com.star.pojo.SecurityUser;
import com.star.repository.UserRepository;
import com.star.pojo.User;
import com.star.util.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户服务
 *
 * @author tanyapeng
 * @date 2021/2/5
 */
@Service("userDetailsService")
@Slf4j
public class UserService implements UserDetailsService {

    @Resource
    private UserRepository userRepository;

    /**
     * 通过名字获取用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        try {
            // 根据用户名查询数据库
            User user = userRepository.selectOne(username, null);
            // 判断
            if (user == null) {
                throw new ServiceException(20001, "用户名不存在!");
            }

            // 根据用户查询用户权限列表
            List<String> list = new ArrayList<>();
            list.add("admin");
            List<String> permissionValueList = list;
            SecurityUser securityUser = new SecurityUser();
            securityUser.setCurrentUserInfo(user);
            securityUser.setPermissionValueList(permissionValueList);
            return securityUser;
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error("loadUserByUsername error - {},{}", ExceptionUtils.getStackTrace(e), username);
            throw new SystemException(10001, "获取用户信息出错");
        }
    }

    /**
     * 校验登录
     *
     * @param username
     * @param password
     * @return
     */
    public User checkUser(String username, String password) {
        User user = userRepository.findByUsernameAndPassword(username, MD5Utils.code(password));
        return user;
    }
}